package com.joint.web.action.mp;

import com.fz.us.base.util.LogUtil;
import com.joint.base.bean.SystemConfig;
import com.joint.base.mp.WxBean;
import com.joint.base.mp.WxMpInCacheConfigStorage;
import com.joint.base.service.AdminService;
import com.joint.base.service.UsersService;
import com.joint.base.util.StringUtils;
import com.joint.web.action.BaseController;
import fz.me.chanjar.weixin.common.api.WxConsts;
import fz.me.chanjar.weixin.common.bean.WxMenu;
import fz.me.chanjar.weixin.common.exception.WxErrorException;
import fz.me.chanjar.weixin.mp.api.WxMpService;
import fz.me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import fz.me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 后台Action类 - 网站注册 - 登录注册
 * ============================================================================
 * 版权所有 2013 min_xu。
 * ----------------------------------------------------------------------------
 * 
 * @author min_xu
 * 
 * @version 0.1 2013-7-15
 */

@Controller("mpLogin")
@RequestMapping(value = "/mp")
public class LoginAction extends BaseController {
	private static final long serialVersionUID = -5383463207248344967L;

	private String username;
	private String openId;
	private String redirectUrl;
	private String nickname;
	private String headimgurl;

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	private String error;
	@Resource
	private UsersService usersService;
	@Resource
	private AdminService adminService;
	@Resource
	private WxMpService wxMpService;

	/**
	 * 区分是否有openId情况，如果没有则使用微信的内置302跳转一次
	 * */
	@RequestMapping(value="/login",method = RequestMethod.GET)
 	public String execute(HttpServletRequest request,HttpServletResponse response) {

		try {
			if(StringUtils.isNotEmpty(openId)){
				error = (String)request.getParameter("state");
				LogUtil.info("{state}" + error);
				WxMpUser wxMpUser = null;
				wxMpUser = wxMpService.userInfo(openId, WxConsts.CN);
				nickname = wxMpUser.getNickname();
				headimgurl = wxMpUser.getHeadImgUrl();
			}else if(StringUtils.isNotEmpty(code)){
				LogUtil.info(code);
				error = (String)request.getParameter("state");
				LogUtil.info("{state}" + error);
				WxMpOAuth2AccessToken oAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
				LogUtil.info("oAuth2AccessToken" + oAuth2AccessToken.toString());
				WxMpUser wxMpUser = wxMpService.userInfo(oAuth2AccessToken.getOpenId(), WxConsts.CN);
				//该接口需要弹出式授权控制，此处不使用！！oauth2getUserInfo(oAuth2AccessToken,WxConsts.CN);
				openId = wxMpUser.getOpenId();
				nickname = wxMpUser.getNickname();
				headimgurl = wxMpUser.getHeadImgUrl();
			}else{
				error = (String)request.getParameter("error");

				try {
					error = UriUtils.encodeQueryParam(error, "utf8");
				} catch (UnsupportedEncodingException e) {
					error = "";
				}

				redirectUrl = wxMpService.oauth2buildAuthorizationUrl("snsapi_base", "");
				LogUtil.info("{redirectUrl}"+redirectUrl);
				try {
					response.sendRedirect(redirectUrl);
				} catch (IOException e) {

				}
			}
		} catch (WxErrorException e) {
			e.printStackTrace();
			error = "【账号异常，请稍后再试】";
		} finally {

		}
		return SUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getOpenId() {
		return openId;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}
	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getHeadimgurl() {
		return headimgurl;
	}

	public void setHeadimgurl(String headimgurl) {
		this.headimgurl = headimgurl;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}



	@Resource
	private WxMpInCacheConfigStorage wxMpConfigStorage;
	@Resource
	private SystemConfig systemConfig;
	public String setAppMenu(){
		String base = wxMpConfigStorage.getHttpHost()+"/"+systemConfig.getWebroot();
		WxMenu menu = new WxMenu();
		WxMenu.WxMenuButton button1 = new WxMenu.WxMenuButton();
		button1.setType(WxConsts.BUTTON_VIEW);
		button1.setName("首页");
		button1.setUrl( base +"/mp/index.action");

		WxMenu.WxMenuButton button2 = new WxMenu.WxMenuButton();
		button2.setType(WxConsts.BUTTON_VIEW);
		button2.setName("知识库");
		button2.setUrl( base + "/mp/ajax!knowledge.action");

		WxMenu.WxMenuButton button3 = new WxMenu.WxMenuButton();
		button3.setName("我的");

		menu.getButtons().add(button1);
		menu.getButtons().add(button2);
		menu.getButtons().add(button3);

		WxMenu.WxMenuButton button31 = new WxMenu.WxMenuButton();
		button31.setType(WxConsts.BUTTON_CLICK);
		button31.setName("账号");
		button31.setKey(WxBean.EventKeyEnum.account.name());

//        WxMenu.WxMenuButton button32 = new WxMenu.WxMenuButton();
//        button32.setType(WxConsts.BUTTON_CLICK);
//        button32.setName("动态");
//        button32.setKey(WxBean.EventKeyEnum.active.name());

		WxMenu.WxMenuButton button33 = new WxMenu.WxMenuButton();
		button33.setType(WxConsts.BUTTON_CLICK);
		button33.setName("反馈");
		button33.setKey(WxBean.EventKeyEnum.feedback.name());

		WxMenu.WxMenuButton button34 = new WxMenu.WxMenuButton();
		button34.setType(WxConsts.BUTTON_CLICK);
		button34.setName("版本");
		button34.setKey(WxBean.EventKeyEnum.version.name());

//        WxMenu.WxMenuButton button35 = new WxMenu.WxMenuButton();
//        button35.setType(WxConsts.BUTTON_CLICK);
//        button35.setName("下载App");
//        button35.setKey(WxBean.EventKeyEnum.download.name());

		button3.getSubButtons().add(button31);
//        button3.getSubButtons().add(button32);
		button3.getSubButtons().add(button33);
		button3.getSubButtons().add(button34);
//        button3.getSubButtons().add(button35);
		LogUtil.info(menu.toJson());
		try {
			wxMpService.menuCreate(menu);
		}catch (WxErrorException e){
			e.printStackTrace();
		}

		return ajaxText("success");
	}
}